package com.dlc.shop.user.api.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.app.vo.ProductVO;
import com.dlc.shop.bean.app.vo.SkuVO;
import com.dlc.shop.bean.event.LoadProdActivistEvent;
import com.dlc.shop.bean.model.UserExtension;
import com.dlc.shop.bean.order.LoadProdActivistOrder;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.util.Arith;
import com.dlc.shop.service.UserExtensionService;
import com.dlc.shop.user.common.dao.UserLevelMapper;
import com.dlc.shop.user.common.model.UserLevel;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;


/**
 * 加载商品会员信息
 * @author yami
 */
@Component("levelProdActivistListener")
@AllArgsConstructor
public class LoadProdActivistListener {

        private UserLevelMapper userLevelMapper;
        private UserExtensionService userExtensionService;


    @EventListener(LoadProdActivistEvent.class)
    @Order(LoadProdActivistOrder.DEFAULT)
    public void loadProdLevelHandle(LoadProdActivistEvent event) {
        ProductVO productVO = event.getProductVO();
        // 只计算店铺会员价
        UserExtension extension = null;
        //用户登录状态时，计算店铺会员价
        if(Objects.nonNull(event.getUserId()) || Objects.equals(event.getUserId(), "")){
            calMemberPrice(event);
            extension = userExtensionService.getOne(
                    new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, event.getUserId()));
            if (Objects.nonNull(extension) && extension.getLevel() == null) {
                extension.setLevel(Constant.USER_LEVEL_INIT);
            }
        }

        UserLevel level = userLevelMapper.selectOneAndCategory(extension, Constant.PLATFORM_SHOP_ID);
        //用户是否是平台付费会员 是则显示对应会员价，否则显示平台最优惠的付费会员价
        Boolean isPlatformMember = Objects.nonNull(extension) && Objects.equals(extension.getLevelType(), 1) && Objects.nonNull(level);
        //获取最优惠的店铺会员价和最优惠的平台会员价
        List<UserLevel> userLevels = userLevelMapper.listLevelAndCategoryByShopId(productVO.getShopId(), null);
        List<UserLevel> platformUserLevels = userLevelMapper.listLevelAndCategoryByShopId( Constant.PLATFORM_SHOP_ID, 1);
//        // 为空不用处理
//        if (CollectionUtil.isEmpty(userLevels)) {
//            return;
//        }
        double minDiscount = 10.0;
        Integer maxBrandLevel = 10;
        Integer brandLevel = 10;
        for (UserLevel userLevel : userLevels) {
            if(Objects.equals(userLevel.getDiscountType(),1) && !userLevel.getCategoryIds().contains(productVO.getCategoryId())){
                continue;
            }
            if(userLevel.getDiscount() < minDiscount){
                minDiscount = userLevel.getDiscount();
                brandLevel = userLevel.getLevel();
            }
        }
        double minPlatformDiscount = 10.0;
        Integer platformLevel = 10;
        for (UserLevel userLevel : platformUserLevels) {
            if(isPlatformMember){
                platformLevel = level.getLevel();
                minPlatformDiscount = level.getDiscount();
                break;
            }
            if(Objects.equals(userLevel.getDiscountType(),1) && !userLevel.getCategoryIds().contains(productVO.getCategoryId())){
                continue;
            }
            if(userLevel.getDiscount() < minPlatformDiscount){
                minPlatformDiscount = userLevel.getDiscount();
                platformLevel = userLevel.getLevel();
            }
        }
        // 放入会员价信息
        for (SkuVO skuVO : productVO.getSkuList()) {
            if(!Objects.equals(brandLevel, maxBrandLevel)){
                skuVO.setMostMemberAmount(Arith.div(Arith.mul(skuVO.getPrice(), minDiscount), 10, 2));
            }
            if(!Objects.equals(platformLevel, maxBrandLevel)) {
                skuVO.setMostPlatformMemberAmount(Arith.div(Arith.mul(skuVO.getPrice(), minPlatformDiscount), 10, 2));
            }
        }
        if(!Objects.equals(brandLevel, maxBrandLevel)) {
            productVO.setMostLevel(brandLevel);
        }
        if(!Objects.equals(platformLevel, maxBrandLevel)) {
            productVO.setMostPlatformLevel(platformLevel);
        }
    }

    private void calMemberPrice(LoadProdActivistEvent event) {
        //获取用户的店铺会员信息
        List<UserLevel> userLevelList = userLevelMapper.listLevelAndCategoryByUserId(event.getUserId(), Collections.singleton(event.getProductVO().getShopId()));
        if(CollectionUtil.isEmpty(userLevelList)){
            return;
        }
        ProductVO productVO = event.getProductVO();
        UserLevel shopLevel = userLevelList.get(0);
        // 店铺商品打折
        boolean isDiscount = shopLevel != null
                && shopLevel.getDiscount() < 10.0
                && (shopLevel.getDiscountType() == 0 || shopLevel.getCategoryIds().contains(productVO.getCategoryId()));
        productVO.setLevel(shopLevel.getLevel());
        // 放入会员价信息
        if(isDiscount){
            productVO.getSkuList().forEach(skuDto -> {
                double memberAmount = Arith.div(Arith.mul(skuDto.getPrice(), shopLevel.getDiscount()), 10, 2);
                memberAmount = Arith.div(Arith.mul(memberAmount, 100), 100, 2);
                skuDto.setMemberAmount(Math.max(memberAmount, 0.01));
            });
        }

    }
}
